package com.kim.rssreader.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.ImageView;

import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndContentImpl;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndEntry;
import com.kim.rssreader.R;
import com.kim.rssreader.adapter.ContentPageAdapter;
import com.kim.rssreader.domain.RssContent;
import com.kim.rssreader.utils.DataFetchCallback;
import com.kim.rssreader.utils.DataFetchService;
import com.kim.rssreader.utils.DateUtil;
import com.kim.rssreader.utils.NetUtil;
import com.kim.rssreader.utils.RssSourceReader;
import com.kim.rssreader.utils.Utils;
import com.kim.rssreader.utils.ValueConstant;
import com.kim.rssreader.view.MyWebChromeClient;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;

public class RssContentViewActivity2 extends BaseActivity implements
		View.OnClickListener, DataFetchCallback {

	private HashMap<String, String> loadStateCache = new HashMap<String, String>();

	public static final int ZOOM = 0x000001;
	public static final int DRAG = 0x000002;
	public static final int NONE = 0x000003;

	public static final int PRE = 0; // 上一篇
	public static final int NEXT = 1; // 下一篇

	public static final String TAG = "RssContentViewActivity";

	ImageView mBack; // 返回按钮
	ImageView mRefresh; // 刷新按钮
	ImageView share;
	ViewPager viewPager = null;
	WebView webView = null;

	private int prePageIndex = 0;

	List<View> views = null;

	String columnId = null;
	String title = null;
	String time = null;
	String url = null;

	List<SyndEntry> entriesLocal = null;

	private String columnFlagStarter = null;
	private String columnFlagEnd = null;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			String url = null;
			switch (msg.what) {
			case ValueConstant.MSG_SHOWCONTENT:
				if (bundle == null) {
					return;
				}
				url = bundle.getString(ValueConstant.DATA_URL);
				String message = bundle.getString(ValueConstant.DATA_MESSAGE);
				showContentImmediately(message, url);
				break;
			case ValueConstant.MSG_SHOWNEXTCONTENT:
				url = bundle.getString(ValueConstant.DATA_URL);
				int pageIndex = bundle.getInt(ValueConstant.DATA_PAGE_INDEX);
				if (msg.obj == null) {
					showNextContent(url, dbDAO.getRssContentEntityByUrl(url),
							pageIndex);
				} else {
					showNextContent(url, (RssContent) msg.obj, pageIndex);
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void initParam() {
		Intent intent = getIntent();
		if (intent != null) {
			url = intent.getStringExtra("url");
			title = intent.getStringExtra("title");
			time = intent.getStringExtra("time");
			columnFlagStarter = intent.getStringExtra("flagStart");
			columnFlagEnd = intent.getStringExtra("flagEnd");
			columnId = intent.getStringExtra("columnId");
			entriesLocal = dbDAO.getColumnItemByColumnId(columnId);
			views = new ArrayList<View>();
			for (int i = 0; i < entriesLocal.size(); i++) {
				views.add(new WebView(this));
			}
		}
	}

	public void initView() {

		setContentView(R.layout.rss_content_view2);
		mBack = (ImageView) findViewById(R.id.iv_back);
		mBack.setOnClickListener(this);

		mRefresh = (ImageView) findViewById(R.id.iv_refresh);
		mRefresh.setOnClickListener(this);
		share = (ImageView) findViewById(R.id.contentview_img_share);
		share.setOnClickListener(this);
		viewPager = (ViewPager) findViewById(R.id.vp_content);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				refreshPage(position);
			}

			@Override
			public void onPageScrolled(int position, float positionOffset,
					int positionOffsetPixels) {
			}

			@Override
			public void onPageScrollStateChanged(int state) {
			}
		});

		viewPager.setAdapter(new ContentPageAdapter(views));
		int startIndex = getTargetIndex(url);
		viewPager.setCurrentItem(startIndex);
		refreshPage(startIndex);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		loadStateCache.clear();
		loadStateCache = null;
		views.clear();
		views = null;
	}

	public void refreshPage(int position) {

		SyndEntry syndEntry = getTargetContent(position);
		url = syndEntry.getLink();
		title = syndEntry.getTitle();
		time = DateUtil.parseDate2Str(syndEntry.getPublishedDate());

		@SuppressWarnings("unchecked")
		List<Object> contents = syndEntry.getContents();
		String content = null;
		if (contents != null && contents.size() > 0) {
			Object object = contents.get(0);
			if (object instanceof SyndContentImpl) {
				content = null;
			} else {
				content = (String) contents.get(0);
			}
		}

		if (content != null && !"".equals(content)) {
			showContentImmediately(content, url);
			return;
		}

		// 网络不可用且内容为空
		if (!NetUtil.isNetAvailable(this)) {
			showContentImmediately(null, url);
			return;
		}

		startRefreshAnim();
		content = DataFetchService.fetchAndPersistant(url, dbDAO,
				columnFlagStarter, columnFlagEnd, this);
		if (content != null) {
			stopRefreshAnim();
			showContentImmediately(content, url);
		}
	}

	/**
	 * 立即显示当前页内容
	 * 
	 * @param content
	 * @param url
	 */
	private void showContentImmediately(String content, String url) {
		webView = findTargetView(viewPager.getCurrentItem());
		if (content == null) {
			webView.loadUrl(ValueConstant.DATA_FETCH_ERROR);
			return;
		}
		
//		CacheManager.getCacheFile(url, null).getInputStream();

		/**
		 * 未加载过，则不处理
		 */
		if (!loadStateCache.containsKey(url)) {
			content = Utils.interceptedContent(content, columnFlagStarter,
					columnFlagEnd);

			webView.loadDataWithBaseURL(url, Utils
					.buildContentWidthLocalImageUrl(this, dbDAO, url, content,
							title, time), "text/html", "utf-8", "");
		}

		// 标记该篇文章为已读
		dbDAO.updateReadState(url);
		// 标记该篇文章为已加载
		loadStateCache.put(url, url);

		// 抓取下一个页面的数据
		String urlNext = null;
		int nextIndex = 0;
		if (viewPager.getCurrentItem() == 0) { // 正在查看第一页
			if (1 == entriesLocal.size()) {
				return;
			}
			nextIndex = 1;
		} else if (viewPager.getCurrentItem() > prePageIndex
				&& (viewPager.getCurrentItem() + 1) < entriesLocal.size()) {
			nextIndex = viewPager.getCurrentItem() + 1;
		} else if (viewPager.getCurrentItem() < prePageIndex
				&& (viewPager.getCurrentItem() - 1) >= 0) {
			nextIndex = viewPager.getCurrentItem() - 1;
		}
		urlNext = getTargetContent(nextIndex).getLink();
		DataFetchService.fetchAndPersistant(urlNext, dbDAO, columnFlagStarter,
				columnFlagEnd, this);
		prePageIndex = viewPager.getCurrentItem();
	}

	/**
	 * 加载下一页内容
	 * 
	 * @param url
	 * @param pageIndex
	 */
	private void showNextContent(String url, RssContent content, int pageIndex) {
		if (loadStateCache.containsKey(url)) {
			return;
		}

		webView = findTargetView(pageIndex);

		if (!NetUtil.isNetAvailable(this) && content == null) {
			webView.loadUrl(ValueConstant.DATA_FETCH_ERROR);
			return;
		}

		if (content == null || "".equals(content.rssContent)) {
			return;
		}

		String contentStr = Utils.interceptedContent(content.rssContent,
				columnFlagStarter, columnFlagEnd);
		webView.loadDataWithBaseURL(url, Utils.buildContentWidthLocalImageUrl(
				this, dbDAO, url, contentStr, content.rssContentTitle,
				content.rssContentTime), "text/html", "utf-8", "");
		loadStateCache.put(url, url);
	}

	/**
	 * 开始刷新动画
	 */
	private void startRefreshAnim() {
		Animation animation = AnimationUtils.loadAnimation(this,
				R.anim.refresh_anim);
		mRefresh.setAnimation(animation);
		animation.start();
	}

	/**
	 * 结束刷新动画
	 */
	private void stopRefreshAnim() {
		Animation animation = mRefresh.getAnimation();
		if (animation != null) {
			animation.cancel();
			animation = null;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.iv_refresh:
			refreshPage(viewPager.getCurrentItem());
			break;
		case R.id.contentview_img_share:
			UMSocialService controller = UMServiceFactory.getUMSocialService("test", RequestType.SOCIAL);
			String shareContent = "美文分享: \n"+"    《"+title+"》  "+url + " ";
			controller.setShareContent(shareContent);
			controller.openShare( this ,false);
			break;
			
		}
	}

	/**
	 * 获取目标内容
	 * 
	 * @param currentUrl
	 * @param dirctFlag
	 * @return
	 */
	private SyndEntry getTargetContent(int index) {

		if (entriesLocal == null || entriesLocal.size() == 0) {
			return null;
		}

		if (index > entriesLocal.size() || index < 0) {
			return null;
		}
		return entriesLocal.get(index);
	}

	/**
	 * 获取目标索引
	 * 
	 * @param currentUrl
	 * @param dirctFlag
	 * @return
	 */
	private int getTargetIndex(String url) {

		if (entriesLocal == null || entriesLocal.size() == 0) {
			return 0;
		}

		for (int i = 0; i < entriesLocal.size(); i++) {
			if (entriesLocal.get(i).getLink().equals(url)) {
				return i;
			}
		}
		return 0;
	}

	@Override
	public void onLocalDataFetched(String url, RssContent content) {
		sendMessageNext(url, getTargetIndex(url), content);
	}

	@Override
	public void onDataFetched(String url, String message) {
		if (!this.url.equals(url)) {
			sendMessageNext(url, getTargetIndex(url));
			return;
		}
		stopRefreshAnim();
		sendMessage(url, message);
	}

	@Override
	public void onError(String url, Throwable throwable) {
		if (!this.url.equals(url)) {
			return;
		}
		stopRefreshAnim();
		sendMessage(null, null);
	}

	private WebView findTargetView(int position) {
		ContentPageAdapter adapter = (ContentPageAdapter) viewPager
				.getAdapter();
		WebView webView = (WebView) adapter.getViews().get(position);
		webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		webView.getSettings().setDefaultTextEncodingName(
				RssSourceReader.ENCODING);
		webView.getSettings().setSupportZoom(false);

		webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		webView.getSettings().setJavaScriptEnabled(true);

		String targetUrl = getTargetContent(position).getLink();
		webView.setWebChromeClient(new MyWebChromeClient(this, dbDAO, targetUrl));
		// webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
		// 网络可用且内容不为空，则不使用cache
		if (NetUtil.isNetAvailable(this)) {
			webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		} else {
			webView.getSettings().setCacheMode(
					WebSettings.LOAD_CACHE_ELSE_NETWORK);
		}
		return webView;
	}

	/**
	 * 发送消息通知当前页面刷新内容
	 * 
	 * @param url
	 * @param message
	 */
	private void sendMessage(String url, String message) {
		Message msg = Message.obtain();
		msg.what = ValueConstant.MSG_SHOWCONTENT;
		Bundle data = new Bundle();
		msg.setData(data);
		data.putString(ValueConstant.DATA_URL, url);
		data.putString(ValueConstant.DATA_MESSAGE, message);
		handler.sendMessage(msg);
	}

	/**
	 * 发送消息通知下一个页面刷新内容
	 * 
	 * @param url
	 */
	private void sendMessageNext(String url, int pageIndex, Object... object) {
		Message msg = Message.obtain();
		msg.what = ValueConstant.MSG_SHOWNEXTCONTENT;
		Bundle data = new Bundle();
		msg.setData(data);
		data.putString(ValueConstant.DATA_URL, url);
		data.putInt(ValueConstant.DATA_PAGE_INDEX, pageIndex);

		if (object != null && object.length == 1) {
			msg.obj = object[0];
		}

		handler.sendMessage(msg);
	}

}